package com.dcbeida.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.dcbeida.MyApplication;
import com.dcbeida.R;
import com.dcbeida.activity.CaptureActivity;
import com.dcbeida.activity.HomeActivity;
import com.dcbeida.activity.msg.MsgActivity;
import com.dcbeida.activity.sales.StoresalesActivity;
import com.dcbeida.activity.store.StoreActivity;
import com.dcbeida.adapter.GalleryAdapter;
import com.dcbeida.bean.DrugListBean;
import com.dcbeida.bean.LengthObj;
import com.dcbeida.bean.MsgBean;
import com.dcbeida.bean.ShopSummary;
import com.dcbeida.bean.ShopSummaryCurrent;
import com.dcbeida.fragment.homeFragment.HomeContract;
import com.dcbeida.fragment.homeFragment.HomePresenter;
import com.dcbeida.listern.OnKeyListener;
import com.dcbeida.mine.MyClientActivity;
import com.dcbeida.utils.SharedPreferencesUtils;
import com.dcbeida.utils.Utils;
import com.umeng.message.PushAgent;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;


/**
 * 首页
 * Created by swt on 2016/11/17.
 */

public class HomeFragment extends BaseFragment implements HomeContract.View {

    @Bind(R.id.tv_shop_name)
    TextView tv_shop_name;

    @Bind(R.id.btnRight)
    ImageView btnRight;
    @Bind(R.id.btnRed)
    ImageView btnRed;

    @Bind(R.id.input_search)
    EditText inputSearch;
    @Bind(R.id.ll_search)
    LinearLayout llSearch;

    @Bind(R.id.lin_mdxs)
    LinearLayout lin_mdxs;

    @Bind(R.id.lin_yprk)
    LinearLayout lin_yprk;

    @Bind(R.id.lin_ypcx)
    LinearLayout lin_ypcx;
    @Bind(R.id.gallery)
    Gallery gallery;
    @Bind(R.id.img_back)
    ImageView imgBack;
    @Bind(R.id.tv_jh_num)
    TextView tvJhNum;
    @Bind(R.id.tv_xl_num)
    TextView tvXlNum;
    @Bind(R.id.tv_kc_num)
    TextView tvKcNum;
    @Bind(R.id.tv_dyxl_num)
    TextView tvDyxlNum;
    @Bind(R.id.tv_dyjh_num)
    TextView tvDyjhNum;
    @Bind(R.id.ll_dyjh)
    RelativeLayout llDyjh;
    @Bind(R.id.tv_dqkc_num)
    TextView tvDqkcNum;
    @Bind(R.id.tv_ksts_num)
    TextView tvKstsNum;
    @Bind(R.id.tv_news)
    TextView tvNews;
    @Bind(R.id.tv_news_time)
    TextView tvNewsTime;
    @Bind(R.id.ll_news)
    LinearLayout llNews;

    private HomePresenter mPresent;

    private PushAgent mPushAgent;
    private MyReceiver myReceiver;
    private MsgReceiver newMsg;

    private GalleryAdapter adapter;
    private List<LengthObj> list;
    private int month;
    private int year;
    private int day;
    private List<ShopSummary.ListBean> shopSummaryList;
    private int maxSales = 0;
    private int maxStock = 0;

    @Override
    public View initViews() {
        View view = View.inflate(mActivity, R.layout.home_fragment, null);
        ButterKnife.bind(this, view);
        return view;
    }

    private int currentPos;//当前的游标置为列表最后一个

    @Override
    public void initData() {
        inputSearch.setFocusable(false);
        Calendar cal = Calendar.getInstance();
        year = cal.get(Calendar.YEAR);
        month = cal.get(Calendar.MONTH) + 1;
        day = cal.get(Calendar.DATE);



        tv_shop_name.setText(R.string.kmn);
        inputSearch.setFocusable(false);
        inputSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {


            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (!TextUtils.isEmpty(inputSearch.getText().toString().trim())) {
                    llSearch.setGravity(Gravity.LEFT | Gravity.CENTER);
                } else {
                    llSearch.setGravity(Gravity.CENTER);
                }
                inputSearch.setGravity(Gravity.LEFT | Gravity.CENTER);
                Drawable img_off = getResources().getDrawable(R.drawable.sousuo);
                //调用setCompoundDrawables时，必须调用Drawable.setBounds()方法,否则图片不显示
                img_off.setBounds(0, 0, img_off.getMinimumWidth(), img_off.getMinimumHeight());
                inputSearch.setCompoundDrawables(img_off, null, null, null); //设置左图标
            }
        });

        Utils.setOnKeySearch(inputSearch, new OnKeyListener() {
            @Override
            public void search() {
                inputSearch.setFocusable(false);

            }
        });


        mPresent = new HomePresenter(this, mActivity);
        if (MyApplication.bindDevicetoken != null)
            mPresent.bindDevicetoken(MyApplication.bindDevicetoken);

        mPresent.getdruglist();

        mPresent.getShopSummaryCurrent();
        if (12 != month) {
            mPresent.getShopSummary(year + "-01-01", year + "-" + (month) + "-" + day + "", "1");
        } else {
            mPresent.getShopSummary(year + "-01-01", Utils.getNowTime(), "1");
        }

        mPresent.getNews("0","1");

        myReceiver = new MyReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(MyApplication.UPDATE_STATUS_ACTION);
        getActivity().registerReceiver(myReceiver, filter);

        newMsg = new MsgReceiver();
        filter = new IntentFilter();
        filter.addAction(MyApplication.NEW_MSG);
        getActivity().registerReceiver(newMsg, filter);


        mPushAgent = PushAgent.getInstance(getActivity());
        mPushAgent.onAppStart();


        adapter = new GalleryAdapter(this.getActivity());
        list = new ArrayList<>();
        //        for (int i = 0; i < month; i++) {
        //            int length = calculateMargTop(i % 10);
        //            list.add(new LengthObj(length));
        //        }

        adapter.setList(list);
        gallery.setAdapter(adapter);
        gallery.setSelection(month - 1);
        gallery.setCallbackDuringFling(false);
        gallery.setUnselectedAlpha(0.5f); // 设置未选中图片的透明度
        currentPos = list.size() - 1;

        //        gallery.setOnTouchListener(new View.OnTouchListener() {
        //            @Override
        //            public boolean onTouch(View v, MotionEvent event) {
        //                Log.i("info2",  "======:" + event.getAction());
        //                return false;
        //            }
        //        });


        gallery.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                currentPos = position;
                ShopSummary.ListBean bean = shopSummaryList.get(position);
                tvXlNum.setText(bean.getSales());
                tvKcNum.setText(bean.getStock());
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }

    private int calculateMargTop(int index, int maxL) {
        if (0 == index) {
            return Utils.convertDip2Pixel(100);//表示柱形图的头部空余位置
        } else {
            double bl = 100 * (1 - ((double)index / (double)maxL));
            if (100 == bl) {
                bl = 100;
            }

            return Utils.convertDip2Pixel((int)Math.rint(bl));//表示柱形图的头部空余位置
        }

    }

    SharedPreferencesUtils sp;

    private void refreshMsg() {
        if (sp == null)
            sp = SharedPreferencesUtils.getInstance(getActivity());
        if (sp.getIsHidden())//消息已读
            btnRed.setVisibility(View.GONE);
        else
            btnRed.setVisibility(View.VISIBLE);
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden) {   // 不在最前端显示 相当于调用了onPause();
        } else {  // 在最前端显示 相当于调用了onResume();
            //刷新数据
            refreshMsg();
        }
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
        getActivity().unregisterReceiver(myReceiver);
        getActivity().unregisterReceiver(newMsg);
    }

    @Override
    public void setPresenter(HomeContract.Present presenter) {

    }

    @Override
    public void showTip(String msg) {
        Utils.showTip(getActivity(), msg);
    }

    @Override
    public void showShopSummaryCurrent(ShopSummaryCurrent data) {
        if(data==null || data.getList()==null){
            tvDyxlNum.setText("0");
            tvDyjhNum.setText("0");
            tvDqkcNum.setText("0");
            tvKstsNum.setText("0");
        }
        else if (null != data.getList() && 0 < data.getList().size()) {
            ShopSummaryCurrent.ListBean listBean = data.getList().get(0);
            tvDyxlNum.setText(listBean.getSales());
            tvDyjhNum.setText(listBean.getStockin());
            tvDqkcNum.setText(listBean.getStock());
            tvKstsNum.setText(listBean.getDaysforsale());
        }

    }

    @Override
    public void showShopSummary(ShopSummary shopSummary) {
        if(shopSummary.getList()==null){
            tvXlNum.setText("0");
            tvKcNum.setText("0");
            return;
        }
        shopSummaryList = shopSummary.getList();
        for (int i = 0; i < shopSummaryList.size(); i++) {
            ShopSummary.ListBean bean = shopSummaryList.get(i);
            if (Integer.parseInt(bean.getSales()) > maxSales) {
                maxSales = Integer.parseInt(bean.getSales());
            }
            if (Integer.parseInt(bean.getStock()) > maxStock) {
                maxStock = Integer.parseInt(bean.getStock());
            }
        }

        if (null != shopSummary.getList() && 0 < shopSummary.getList().size()) {
            if(maxSales<maxStock){
                maxSales = maxStock;
            }
            for (int i = 0; i < shopSummary.getList().size(); i++) {
                int length = calculateMargTop((Integer.parseInt(shopSummary.getList().get(i).getSales())), maxSales);
                int length2 = calculateMargTop((Integer.parseInt(shopSummary.getList().get(i).getStock())), maxSales);
                list.add(new LengthObj(length, length2));
            }
        }
        ShopSummary.ListBean bean = shopSummary.getList().get(shopSummary.getList().size() - 1);
        tvXlNum.setText(bean.getSales());
        tvKcNum.setText(bean.getStock());
        gallery.setSelection(month - 1);
        adapter.notifyDataSetChanged();
    }

    @Override
    public void showNews(ArrayList<MsgBean> list) {
        if (null!=list&&0<list.size()){
            llNews.setVisibility(View.VISIBLE);
            MsgBean bean = list.get(0);
            tvNews.setText(bean.getTitle());
            tvNewsTime.setText(bean.getCreatetime());
        }else {
            llNews.setVisibility(View.GONE);
        }
    }

    @Override
    public void showDrugIds(DrugListBean data) {

    }

    @Override
    public void logout() {

    }

    @Override
    public void logoutTips() {

    }

    @Override
    public void handleMsg(int count) {

    }


    class MyReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (MyApplication.bindDevicetoken != null)
                mPresent.bindDevicetoken(MyApplication.bindDevicetoken);
        }
    }

    class MsgReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            refreshMsg();
        }
    }

    @OnClick({R.id.input_search, R.id.ll_search, R.id.btnRight, R.id.lin_mdxs, R.id.lin_yprk, R.id.lin_ypcx, R.id.ll_news})
    public void onClick(View view) {
        Bundle bundle = new Bundle();
        switch (view.getId()) {
            case R.id.input_search:
            case R.id.ll_search:
//                hideKeyBoard();
                bundle.putString("search","search");
                ((HomeActivity) getActivity()).showActivity(MyClientActivity.class, bundle);
                break;
            case R.id.btnRight:
                ((HomeActivity) getActivity()).showActivity(MsgActivity.class, null);
                break;
            case R.id.ll_news:
                ((HomeActivity) getActivity()).showActivity(MsgActivity.class, null);
                break;
            case R.id.lin_mdxs:
                ((HomeActivity) mActivity).showActivity(StoresalesActivity.class, null);
                break;
            case R.id.lin_yprk:
                ((HomeActivity) mActivity).showActivity(StoreActivity.class, null);
                break;
            case R.id.lin_ypcx:
                ((HomeActivity) mActivity).showActivity(CaptureActivity.class, null);
                break;
        }
    }

    // 隐藏键盘
    private void hideKeyBoard() {
        setFocus(inputSearch, true);
        InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(inputSearch, InputMethodManager.HIDE_NOT_ALWAYS);
    }

    public void setFocus(EditText editText, boolean focusable) {
        editText.setFocusable(focusable);
        editText.setFocusableInTouchMode(focusable);
        editText.requestFocus();
        editText.requestFocusFromTouch();
    }
}
